package com.fsg.user.provider;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fsg.common.request.user.ReqUser;
import com.fsg.common.response.ResultBean;
import com.fsg.user.config.elastic.UserRepository;
import com.fsg.user.config.exception.BizException;
import com.fsg.user.config.stream.logtest.MyProcessor;
import com.fsg.user.config.stream.usermq.TopicUserGateway;
import com.fsg.user.config.stream.usermq.TopicUserSource;
import com.fsg.user.constant.ErrorEnum;
import com.fsg.user.entity.User;
import com.fsg.user.mapper.elastic.EsUserDao;
import com.fsg.user.mapper.elastic.EsVendorDao;
import com.fsg.user.model.MapPathDto;
import com.fsg.user.service.EsVendorService;
import com.fsg.user.service.UserService;
import com.fsg.user.util.RedisUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.RandomStringUtils;
//import org.elasticsearch.search.SearchExtBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;

import io.swagger.annotations.ApiOperation;
import net.sf.jsqlparser.statement.select.KSQLJoinWindow.TimeUnit;
import springfox.documentation.annotations.ApiIgnore;




/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lfz
 * @since 2020-05-01
 */
@Controller
//@RequestMapping("/user")
public class UserController {
	@Autowired
	UserService userService;

	@Autowired
	DiscoveryClient client;


	//	@Autowired
	//    private ElasticsearchTemplate elasticsearchTemplate;

	//@Autowired
	UserRepository userRepository;

	@Autowired
	TopicUserSource topicUserSoure;

	@Autowired
	RedisUtil redisUtil;
	//@Autowired

	Logger log =LoggerFactory.getLogger(UserController.class);

	@GetMapping("/hello")
	@ResponseBody
	public String getHello() {
		List<ServiceInstance> instances = client.getInstances("User");
		ServiceInstance selectedInstance = instances
				.get(0);
		return "Hello World: " + selectedInstance.getServiceId() + ":" + selectedInstance
				.getHost() + ":" + selectedInstance.getPort();
	}

//	@Autowired(required = false)
//	private EsVendorDao vendorDao;
//	@GetMapping("/addIndex")
//	public long addIndex() {
//
//		return vendorDao.count();
//	}
	
//	@Autowired(required = false)
//	private  EsUserDao userDao;
//	@GetMapping("/getUser")
//	public String  getUser() {
//		Long a =userDao.count();
//		return a.toString();
//	}

	@GetMapping("/delIndex")
	public String delIndex() {
		//elasticsearchTemplate.deleteIndex("user");
		return "index";
	}

	@GetMapping("/main")
	public ModelAndView login(String url) {
		ModelAndView modelAndView = new ModelAndView("login");
		modelAndView.addObject("url", url);
		return modelAndView;
	}


	@GetMapping("/name")
	@ResponseBody
	public List<User> getUserName(String address) {
		List<User> users= userRepository.findByAddressLike(address);
		return users;
	}

	@GetMapping("/initUser")
	@ResponseBody
	public List<User> initUser(String address) {
		List<User> users= userRepository.findByAddressLike(address);
		return users;
	}

	@GetMapping("/")
	public String index() {
		return "index";
	}



	@GetMapping("/count")
	@ResponseBody
	public Object count() {
		/*
		 * // try { // //Thread.sleep(6000l); // } catch (InterruptedException e) { //
		 * // TODO Auto-generated catch block // e.printStackTrace(); // }
		 */		return userService.count();

	}

	@ResponseBody
	@ApiOperation(value="判断用户是否存在", notes="根据user的name来判断用户是否存在")
	//@ApiImplicitParam(name = "name", value = "用户Name")
	@RequestMapping(value = "/existUser",method =RequestMethod.GET, produces = { "application/json;charset=UTF-8"})
	public ResultBean<Boolean> existUser(@RequestParam("name") String name) {
		QueryWrapper<User> queryWrapper =new QueryWrapper<>();
		queryWrapper.eq("name", name);
		User user = userService.getOne(queryWrapper);
		log.info("用户：{}校验是否存在{}",name,ObjectUtils.isEmpty(user));
		return new ResultBean<Boolean>(!ObjectUtils.isEmpty(user));
	}

	@ResponseBody
	@ApiOperation(value="创建用户", notes="根据User对象创建用户")
	//@ApiImplicitParam(name = "name", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/", method=RequestMethod.POST,produces = { "application/json;charset=UTF-8" })
	public ResultBean<String> register(@RequestBody @Valid ReqUser reqUser)  {
		QueryWrapper<User> queryWrapper =new QueryWrapper<>();
		queryWrapper.eq("name", reqUser.getName());
		User existUser = userService.getOne(queryWrapper);
		log.info("用户：{}存在:{}",reqUser.getName(),!ObjectUtils.isEmpty(existUser));
		if(!ObjectUtils.isEmpty(existUser)) {
			return new ResultBean<String>("1000","用户已存在");
		}
		User user =new User();
		BeanUtils.copyProperties(reqUser, user);
		user.setCreatedTime(new Date());

		boolean addFlag =userService.save(user);
		log.info("用户：{}注册成功{}",user.getName(),addFlag);
		if(addFlag) {
			topicUserGateway.sendRegisterMsg(user.getName());
		}
		return new ResultBean<String>(String.valueOf(user.getId()));
	}

	public static void main(String[] args) {
		String num=RandomStringUtils.randomAlphabetic(6);

		System.err.println(num);
	}
	//	@RequestMapping("/verifiCode")
	//	@ApiIgnore
	//	public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
	//			throws Exception {
	//		byte[] captchaChallengeAsJpeg = null;
	//		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
	//		try {
	//			// 生产验证码字符串并保存到session中
	//			String createText = defaultKaptcha.createText();
	//			httpServletRequest.getSession().setAttribute("vrifyCode", createText);
	//			// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
	//			BufferedImage challenge = defaultKaptcha.createImage(createText);
	//			ImageIO.write(challenge, "jpg", jpegOutputStream);
	//		} catch (IllegalArgumentException e) {
	//			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
	//			return;
	//		}
	//
	//		// 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
	//		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
	//		httpServletResponse.setHeader("Cache-Control", "no-store");
	//		httpServletResponse.setHeader("Pragma", "no-cache");
	//		httpServletResponse.setDateHeader("Expires", 0);
	//		httpServletResponse.setContentType("image/jpeg");
	//		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
	//		responseOutputStream.write(captchaChallengeAsJpeg);
	//		responseOutputStream.flush();
	//		responseOutputStream.close();
	//	}

	public ResultBean fallbackLogin(ReqUser requser,Throwable throwable) {
		log.info("fallback{}",throwable);
		return new ResultBean("500","处理失败，请稍后重试");

	}

	@ResponseBody
	@ApiIgnore
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	//@Cacheable(value="userCache", key= "'"+RedisKeyContonts.LOGIN_USER+"'+#name")
	@HystrixCommand(fallbackMethod="fallbackLogin")
	public ResultBean<User> login(@Valid @RequestBody ReqUser requser,
			HttpServletRequest httpServletRequest) throws BizException, InterruptedException {
		// 返回参数
		ResultBean<User> resultBean = new ResultBean<>();
		// 校验码
		User user = new User();
		BeanUtils.copyProperties(requser, user);
		QueryWrapper<User> queryWrapper =new QueryWrapper<>();
		queryWrapper.eq("name", requser.getName());
		queryWrapper.eq("password", requser.getPassword());
		User findUser = userService.getOne(queryWrapper);
		if (findUser == null) {
			return new 	ResultBean<>(ErrorEnum.LOGIN_NOTPASS.getErrorCode(),ErrorEnum.LOGIN_NOTPASS.getDefaultMessage());
		}
		//登陆成功mq消息
		//topicUserGateway.sendLoginMsg(user.getName());
		//用户名+时间戳（这里只是demo，正常项目的令牌应该要更为复杂）
		//String flag = requser.getName();
		//redisUtil.set(flag, flag, 180L,java.util.concurrent.TimeUnit.SECONDS);
		resultBean.setData(findUser);
		return resultBean;
	}

	@ApiIgnore
	@ResponseBody
	@RequestMapping(value = "/getUser",method =RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
	public ResultBean<User> findUserInfo(ReqUser requser) {
		QueryWrapper<User> queryWrapper =new QueryWrapper<>();
		queryWrapper.eq("name", requser.getName());
		User user = userService.getOne(queryWrapper);
		return new ResultBean<User>(user);
	}

	@Autowired
	MyProcessor myProcessor;
	@Autowired
	TopicUserGateway topicUserGateway;
	@ApiIgnore
	@ResponseBody
	@RequestMapping(value = "/testMq",method =RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
	public String testMq(String message) {
		//		Message<String> stringMessage = org.springframework.messaging.support.MessageBuilder.withPayload(message).build();
		//        myProcessor.logOutput().send(stringMessage);
		//topicUserGateway.generate("yyyyyy");
		return "ok";
	}
	
	@ResponseBody
	@ApiIgnore
	@RequestMapping(value = "/sso/login", method = RequestMethod.POST)
	//@Cacheable(value="userCache", key= "'"+RedisKeyContonts.LOGIN_USER+"'+#name")
	@HystrixCommand(fallbackMethod="fallbackLogin")
	public ResultBean<User> ssoLogin(@Valid @RequestBody ReqUser requser) throws BizException, InterruptedException {
		// 返回参数
		ResultBean<User> resultBean = new ResultBean<>();
		//oAuthS
		return resultBean;
	}
	
	

}

